import type { PayloadAction } from '@reduxjs/toolkit';
import { createSelector, createSlice } from '@reduxjs/toolkit';

import { getToken, getUserInfo } from './shared';

const initialState = {
  token: getToken(),
  userInfo: getUserInfo(),
};

const authSlice = createSlice({
  initialState,
  name: 'auth',
  reducers: {
    resetAuth: () => initialState,
    setToken: (state, { payload }: PayloadAction<string>) => {
      state.token = payload;
    },
    setUserInfo: (state, { payload }: PayloadAction<Api.Auth.UserInfo>) => {
      state.userInfo = payload;
    },
  },
  selectors: {
    selectToken: (state) => state.token,
    selectUserInfo: (state) => state.userInfo,
  },
});

const { resetAuth, setToken, setUserInfo } = authSlice.actions;

const { selectToken, selectUserInfo } = authSlice.selectors;

const getIsLogin = createSelector([selectToken], (token) => Boolean(token));

const isStaticSuper = createSelector([selectUserInfo], (userInfo) => {
  const PUBLIC_STATIC_SUPER_ROLE = import.meta.env.PUBLIC_STATIC_SUPER_ROLE;
  const PUBLIC_AUTH_ROUTE_MODE = import.meta.env.PUBLIC_AUTH_ROUTE_MODE;
  return PUBLIC_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(PUBLIC_STATIC_SUPER_ROLE);
});

export { authSlice, resetAuth, setToken, setUserInfo, selectToken, selectUserInfo, getIsLogin, isStaticSuper };
